package files;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: paramInListToJSONUtil
 * @Description: paramInList to json
 * @Author: zyy
 * @Date: 2020/08/16 17:13
 * @Version: 1.0
 */
public class paramInListToJSONUtil {

    public static JSONObject deal(List<Map<String, Object>> paramInList) {
        if (paramInList == null || paramInList.size() == 0) {
            return null;
        }
        JSONObject json = new JSONObject();
        for (Map<String, Object> paramInMap : paramInList) {
            recursion(paramInMap, json);
        }
        return json;

    }

    private static void recursion(Map<String, Object> nodeMap, JSONObject json) {
        if (nodeMap == null || nodeMap.isEmpty()) {
            return;
        }
        //判断是否有子节点
        List<Map<String, Object>> subNodeList = (List<Map<String, Object>>) nodeMap.get("subNodeList");
        if (subNodeList == null || subNodeList.size() == 0) {
            //TODO 没有子节点（直接放   准确一点应该判断类型然后放进去）
//            String nodeType = (String) nodeMap.get("nodeType");
            String nodeName = (String) nodeMap.get("nodeName");
            json.put(nodeName, nodeMap.get("nodeDesc"));
            return;
        }

        //有子节点
        String nodeType = (String) nodeMap.get("nodeType");
        String nodeName = (String) nodeMap.get("nodeName");

        if ("List".equals(nodeType)) {
            JSONArray childNodeJSONArray = new JSONArray();
            JSONObject childNodeJSON = new JSONObject();
            for (Map<String, Object> childNodeMap : subNodeList) {
                recursion(childNodeMap, childNodeJSON);
            }
            childNodeJSONArray.add(childNodeJSON);
            json.put(nodeName, childNodeJSONArray);
        } else if ("Map".equals(nodeType)) {
            JSONObject childNodeJSON = new JSONObject();
            for (Map<String, Object> childNodeMap : subNodeList) {
                recursion(childNodeMap, childNodeJSON);
            }
            json.put(nodeName, childNodeJSON);

        } else {
            //默认也是Map处理
            JSONObject childNodeJSON = new JSONObject();
            for (Map<String, Object> childNodeMap : subNodeList) {
                recursion(childNodeMap, childNodeJSON);
            }
            json.put(nodeName, childNodeJSON);
        }
    }

}
